<template>
  <div>
    <el-form :inline="true">
      <el-form-item>
        <el-input
          v-model="searchForm.apply_no"
          placeholder="请输入申请编号"
          clearable
        >
        </el-input>
      </el-form-item>

      <el-form-item>
        <el-select v-model="searchForm.assign_status" placeholder="指派状态">
          <el-option label="全部" :value="''"></el-option>
          <el-option label="待指派" :value="0"></el-option>
          <el-option label="已指派" :value="1"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button @click="getAssignList">查询</el-button>
      </el-form-item>

      <el-form-item>
        <el-button @click="resetSearch">重置</el-button>
      </el-form-item>
    </el-form>

    <el-table
      :data="tableData"
      tooltip-effect="dark"
      style="width: 100%"
      border
      stripe
    >
      <el-table-column prop="requestCode" label="申请编号"> </el-table-column>
      <el-table-column prop="deviceName" label="设备名称"> </el-table-column>
      <el-table-column prop="deviceCode" label="设备编号"> </el-table-column>
      <el-table-column prop="faultDescription" label="故障描述">
      </el-table-column>
      <el-table-column prop="repairUserName" label="维修人员">
      </el-table-column>
      <el-table-column prop="created" label="指派时间"> </el-table-column>
      <el-table-column prop="status" label="指派状态">
        <template slot-scope="scope">
          <el-tag size="small" :type="getStatusType(scope.row.status)">{{
            getStatusText(scope.row.status)
          }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button type="text" @click="detailHandle(scope.row.id)"
            >详情</el-button
          >
          <el-divider direction="vertical"></el-divider>

          <template v-if="scope.row.status === 1">
            <el-button type="text" @click="processAssign(scope.row.id)"
              >指派维修</el-button
            >
          </template>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      layout="total, sizes, prev, pager, next, jumper"
      :page-sizes="[10, 20, 50, 100]"
      :current-page="page_num"
      :page-size="page_size"
      :total="total"
    >
    </el-pagination>

    <!--指派对话框-->
    <el-dialog
      title="指派维修"
      :visible.sync="processDialogVisible"
      width="500px"
    >
      <el-form :model="processForm" :rules="processFormRules" ref="processForm">
        <el-form-item label="维修人员" prop="maintainer_id" label-width="120px">
          <el-select
            v-model="processForm.maintainer_id"
            placeholder="请选择维修人员"
          >
            <el-option
              v-for="user in userList"
              :key="user.id"
              :label="user.username"
              :value="user.id"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="指派时间" prop="assign_time" label-width="120px">
          <el-date-picker
            v-model="processForm.assign_time"
            type="datetime"
            placeholder="选择日期时间"
          ></el-date-picker>
        </el-form-item>

        <el-form-item label="指派备注" prop="assign_note" label-width="120px">
          <el-input
            v-model.trim="processForm.assign_note"
            type="textarea"
            rows="3"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="processDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitProcessForm">确 定</el-button>
      </div>
    </el-dialog>

    <!--详情对话框-->
    <el-dialog title="申请详情" :visible.sync="detailVisible" width="600px">
      <el-form :model="detailForm" label-width="120px">
        <el-form-item label="申请编号">
          <span>{{ detailForm.requestCode }}</span>
        </el-form-item>
        <el-form-item label="设备名称">
          <span>{{ detailForm.deviceName || "未获取到设备信息" }}</span>
        </el-form-item>
        <el-form-item label="设备编号">
          <span>{{ detailForm.deviceCode || "未获取到设备信息" }}</span>
        </el-form-item>
        <el-form-item label="故障描述">
          <span>{{ detailForm.faultDescription }}</span>
        </el-form-item>
        <el-form-item label="申请时间">
          <span>{{ detailForm.requestTime }}</span>
        </el-form-item>
        <el-form-item label="维修人员" v-if="detailForm.repairUserName">
          <span>{{ detailForm.repairUserName }}</span>
        </el-form-item>
        <el-form-item label="指派时间" v-if="detailForm.created">
          <span>{{ detailForm.created }}</span>
        </el-form-item>
        <el-form-item label="完成时间" v-if="detailForm.completionTime">
          <span>{{ detailForm.completionTime }}</span>
        </el-form-item>
        <el-form-item label="维修备注" v-if="detailForm.repairRemarks">
          <span>{{ detailForm.repairRemarks }}</span>
        </el-form-item>
        <el-form-item label="预计费用" v-if="detailForm.estimatedCost">
          <span>{{ detailForm.estimatedCost }}</span>
        </el-form-item>
        <el-form-item label="实际费用" v-if="detailForm.actualCost">
          <span>{{ detailForm.actualCost }}</span>
        </el-form-item>
        <el-form-item label="指派状态">
          <el-tag size="small" :type="getStatusType(detailForm.status)">{{
            getStatusText(detailForm.status)
          }}</el-tag>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="detailVisible = false">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import repairApi from "@/api/repair-request.js";
import userApi from "@/api/sys-user.js";
import deviceApi from "@/api/device.js";
export default {
  name: "MaintenanceAssign",
  data() {
    return {
      searchForm: {
        apply_no: "",
        device_name: "",
        assign_status: "",
      },
      total: 0,
      page_size: 10,
      page_num: 1,

      processDialogVisible: false,
      detailVisible: false,
      processForm: {
        id: "",
        maintainer_id: "",
        assign_time: new Date(),
        assign_note: "",
      },
      detailForm: {},
      userList: [],
      userMap: {},
      deviceList: [],
      deviceMap: {},

      tableData: [],

      processFormRules: {
        maintainer_id: [
          { required: true, message: "请选择维修人员", trigger: "blur" },
        ],
        assign_time: [
          { required: true, message: "请选择指派时间", trigger: "blur" },
        ],
      },
    };
  },
  async created() {
    await this.loadSelectData();
    this.getAssignList();

    this.loadDeviceList();
  },
  methods: {
    // 获取状态文本
    getStatusText(status) {
      const statusMap = {
        1: "待指派",
        2: "维修中",
        3: "已完成",
        4: "已关闭",
      };
      return statusMap[status] || "未知状态";
    },
    // 获取状态对应的标签类型
    getStatusType(status) {
      const typeMap = {
        1: "warning",
        2: "info",
        3: "success",
        4: "danger",
      };
      return typeMap[status] || "default";
    },
    handleSizeChange(val) {
      this.page_size = val;
      this.getAssignList();
    },
    handleCurrentChange(val) {
      this.page_num = val;
      this.getAssignList();
    },
    resetSearch() {
      this.searchForm = {
        apply_no: "",
        device_name: "",
        assign_status: "",
      };
      this.getAssignList();
    },
    loadSelectData() {
      // 加载维修人员列表
      return userApi
        .list()
        .then((res) => {
          if (res && res.data) {
            // 处理可能是分页数据或直接数组的情况
            const data = Array.isArray(res.data)
              ? res.data
              : res.data.records || [];
            this.userList = data;
            // 构建用户映射表
            data.forEach((user) => {
              this.userMap[user.id] = user.username;
              // this.$set(this.userMap, user.id, user.username )
            });
          } else {
            this.userList = [];
          }
        })
        .catch((error) => {
          this.userList = [];
          this.$message.error(
            "获取维修人员列表失败：" + (error.message || "未知错误")
          );
          console.error("获取维修人员列表失败:", error);
          // 为已知的维修人员ID设置默认值
          this.userMap = {};
        });
    },
    loadDeviceList() {
      // 加载设备列表
      deviceApi
        .list()
        .then((res) => {
          if (res && res.data) {
            // 处理可能是分页数据或直接数组的情况
            const data = Array.isArray(res.data)
              ? res.data
              : res.data.records || [];
            this.deviceList = data;
            // 构建设备映射表
            data.forEach((device) => {
              this.deviceMap[device.id] = {
                deviceName: device.deviceName || "未知设备",
                deviceCode: device.deviceCode || "未知编号",
              };
            });
            // 重新获取列表以更新设备信息
            if (this.tableData.length > 0) {
              this.updateTableDataWithDetails();
            }
          } else {
            this.deviceList = [];
          }
        })
        .catch((error) => {
          this.deviceList = [];
          this.$message.error(
            "获取设备列表失败：" + (error.message || "未知错误")
          );
          console.error("获取设备列表失败:", error);
          // 为已知的设备ID设置默认值
          this.deviceMap = {};
        });
    },
    getAssignList() {
      repairApi
        .list({
          requestCode: this.searchForm.apply_no,
          deviceName: this.searchForm.device_name,
          status: this.searchForm.assign_status,
          page_num: this.page_num,
          page_size: this.page_size,
        })
        .then((res) => {
          if (res && res.data) {
            // 处理返回的数据
            const rawData = Array.isArray(res.data)
              ? res.data
              : res.data.records || [];
            // 更新表格数据，填充设备和用户信息
            this.tableData = rawData.map((item) => {
              // 获取设备信息
              const deviceInfo = this.deviceMap[item.deviceId] || {
                deviceName: "加载中...",
                deviceCode: "加载中...",
              };
              // 获取用户信息
              const repairUserName =
                this.userMap[item.repairUserId] ||
                (item.repairUserId ? "加载中..." : "-");

              return {
                ...item,
                deviceName: deviceInfo.deviceName,
                deviceCode: deviceInfo.deviceCode,
                repairUserName: repairUserName,
              };
            });
            this.page_size = res.data.page_size || this.page_size;
            this.page_num = res.data.page_num || this.page_num;
            this.total =
              res.data.total || (Array.isArray(res.data) ? res.data.length : 0);
          } else {
            this.tableData = [];
            this.total = 0;
          }
        })
        .catch((error) => {
          this.tableData = [];
          this.total = 0;
          this.$message.error(
            "获取维修指派列表失败：" + (error.message || "未知错误")
          );
          console.error("获取维修指派列表失败:", error);
        });
    },
    // 更新表格数据中的设备和用户详情
    updateTableDataWithDetails() {
      this.tableData = this.tableData.map((item) => {
        const deviceInfo = this.deviceMap[item.deviceId] || {
          deviceName: "未知设备",
          deviceCode: "未知编号",
        };
        const repairUserName =
          this.userMap[item.repairUserId] ||
          (item.repairUserId ? "未知用户" : "-");

        return {
          ...item,
          deviceName: deviceInfo.deviceName,
          deviceCode: deviceInfo.deviceCode,
          repairUserName: repairUserName,
        };
      });
    },
    processAssign(id) {
      this.processForm = {
        id: id,
        maintainer_id: "",
        assign_time: new Date(),
        assign_note: "",
      };
      this.processDialogVisible = true;
    },
    submitProcessForm() {
      this.$refs["processForm"].validate((valid) => {
        if (valid) {
          // 调整字段名以匹配API要求 - 根据后端AssignDto
          const formData = {
            requestId: this.processForm.id,
            assigneeId: this.processForm.maintainer_id,
            repairRemarks: this.processForm.assign_note, // 添加指派备注
          };
          repairApi
            .assign(formData)
            .then((res) => {
              this.$message({
                showClose: true,
                message: "指派成功",
                type: "success",
              });
              this.getAssignList();
              this.processDialogVisible = false;
            })
            .catch((error) => {
              this.$message.error("指派失败：" + (error.message || "未知错误"));
              console.error("指派维修失败:", error);
            });
        } else {
          return false;
        }
      });
    },
    detailHandle(id) {
      repairApi
        .detail(id)
        .then((res) => {
          // 确保字段名称匹配
          if (res && res.data) {
            // 直接使用返回的数据，并填充设备和用户信息
            const rawData = res.data;
            const deviceInfo = this.deviceMap[rawData.deviceId] || {
              deviceName: "未知设备",
              deviceCode: "未知编号",
            };
            const repairUserName =
              this.userMap[rawData.repairUserId] ||
              (rawData.repairUserId ? "未知用户" : "-");

            this.detailForm = {
              ...rawData,
              deviceName: deviceInfo.deviceName,
              deviceCode: deviceInfo.deviceCode,
              repairUserName: repairUserName,
            };
            this.detailVisible = true;
          } else {
            this.$message.error("获取数据失败：未找到相关信息");
          }
        })
        .catch((error) => {
          this.$message.error(
            "获取维修申请详情失败：" + (error.message || "未知错误")
          );
          console.error("获取维修申请详情失败:", error);
        });
    },
  },
};
</script>

<style scoped>
.el-pagination {
  float: right;
  margin-top: 22px;
}
</style>